<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>股票历史数据查询</title>
</head>
<body>
    <div class="container">
        <h2 class="title">股票历史数据查询</h2>
        <div class="search-box">
            <textarea 
                class="stock-input" 
                id="stockCodes" 
                placeholder="请输入股票代码，多个代码用逗号或换行分隔&#10;例如：002366,000001"
                rows="3"
            ></textarea>
            <div class="button-group">
                <div class="days-input-container">
                    <label for="daysInput">获取天数：</label>
                    <input 
                        type="number" 
                        id="daysInput" 
                        class="days-input" 
                        value="10" 
                        min="1" 
                        max="100"
                    >
                </div>
                <button class="search-btn" onclick="handleSearch()">查询数据</button>
                <button class="copy-btn" id="copyMarkdown" disabled onclick="handleCopyMarkdown()">复制Markdown内容</button>
            </div>
        </div>
        <div class="data-container" id="stockData"></div>
    </div>

    <script>
        // 存储所有回调函数的计数器
        let callbackCounter = 0;
        // 存储所有股票数据的对象
        let stockDataMap = {};

        // 获取最近5个交易日的日期范围
        function getDateRange() {
            const end = new Date();
            const start = new Date();
            const days = parseInt(document.getElementById('daysInput').value) || 10;
            start.setDate(start.getDate() - (days * 2)); // 往前多取两倍的天数，因为要考虑非交易日

            return {
                from: formatDate(start),
                to: formatDate(end)
            };
        }

        // 格式化日期为YYYY-MM-DD
        function formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }
        
        // 处理查询按钮点击
        function handleSearch() {
            // 禁用复制按钮
            document.getElementById('copyMarkdown').disabled = true;
            
            const dateRange = getDateRange();
            console.log(dateRange);
            const input = document.getElementById('stockCodes').value;
            if (!input.trim()) {
                alert('请输入股票代码');
                return;
            }

            // 清空之前的数据
            stockDataMap = {};
            document.getElementById('stockData').innerHTML = '<div class="loading">数据加载中...</div>';

            // 处理输入的股票代码
            const codes = input.split(/[,\n]/)
                .map(code => code.trim())
                .filter(code => code)
                .map(code => {
                    // 移除可能已经存在的sz或sh前缀
                    code = code.toLowerCase().replace(/^(sz|sh)/, '');
                    // 判断是深市还是沪市
                    if (code.startsWith('6')) {
                        return 'sh' + code;
                    } else if (code.startsWith('0') || code.startsWith('3')) {
                        // 对于创业板（3开头）和深市主板（0开头）都返回sz前缀
                        return 'sz' + code;
                    } else if (code.match(/^[0-9]{6}$/)) {
                        // 如果是6位数字但不是以0、3、6开头，给出提示
                        alert('请输入有效的股票代码，目前支持：\n- 上证主板（6开头）\n- 深证主板（0开头）\n- 创业板（3开头）');
                        return null;
                    }
                    return null;
                })
                .filter(code => code !== null);

            if (codes.length === 0) {
                alert('请输入有效的股票代码');
                return;
            }

            // 获取每个股票的数据
            codes.forEach(fetchStockData);
        }

        // 生成Markdown格式的数据
        function generateMarkdown(stockDataMap) {
            const now = new Date();
            const markdownParts = [];
            // 处理每只股票的数据
            Object.entries(stockDataMap).forEach(([code, data]) => {
                if (!data || data === 'error') {
                    markdownParts.push(`\n## ${code}\n`);
                    markdownParts.push('暂无数据或获取失败\n');
                    return;
                }

                // 添加股票标题
                markdownParts.push(`\n## ${code}\n`);

                // 添加表头
                markdownParts.push('| 日期 | 开盘 | 收盘 | 最高 | 最低 | 涨跌幅 | 成交量(万) | MA5 | MA10 |');
                markdownParts.push('|------|------|------|------|------|--------|------------|-----|------|');

                // 只取前10个交易日的数据
                const days = parseInt(document.getElementById('daysInput').value) || 10;
                const recentData = data.slice(0, days);
                
                // 添加数据行
                recentData.forEach((day, index) => {
                    const changePercent = calculateChange(
                        day.close,
                        index < recentData.length - 1 ? recentData[index + 1].close : null
                    );
                    
                    markdownParts.push(
                        `| ${day.day} | ${formatNumber(day.open)} | ${formatNumber(day.close)} | ` +
                        `${formatNumber(day.high)} | ${formatNumber(day.low)} | ${changePercent} | ` +
                        `${(day.volume / 10000).toFixed(2)} | ${formatNumber(day.ma_price5)} | ${formatNumber(day.ma_price10)} |`
                    );
                });

                markdownParts.push('\n'); // 添加空行
            });

            return markdownParts.join('\n');
        }

        // 创建动态回调函数
        function createCallback(stockCode) {
            const callbackName = `jsonpCallback_${callbackCounter++}`;
            window[callbackName] = function(data) {
                if (data && data.length > 0) {
                    // 按日期排序，最新日期在前
                    stockDataMap[stockCode] = data.sort((a, b) => new Date(b.day) - new Date(a.day));
                } else {
                    stockDataMap[stockCode] = null;
                }
                displayAllData();

                // 当所有股票数据都获取完成时，输出Markdown
                const allStocksLoaded = Object.keys(stockDataMap).length === document.getElementById('stockCodes').value
                    .split(/[,\n]/)
                    .map(code => code.trim())
                    .filter(code => code)
                    .length;

                if (allStocksLoaded) {
                    const markdown = generateMarkdown(stockDataMap);
                    console.log('Markdown格式的数据：\n\n' + markdown);
                    // 启用复制按钮
                    document.getElementById('copyMarkdown').disabled = false;
                }

                // 清理回调函数
                delete window[callbackName];
            };
            return callbackName;
        }

        // 获取股票数据
        function fetchStockData(stockCode) {
            // 清除之前的script标签
            const oldScript = document.getElementById(`jsonp-script-${stockCode}`);
            if (oldScript) {
                oldScript.remove();
            }

            const baseUrl = 'https://quotes.sina.cn/cn/api/jsonp_v2.php';
            const callback = createCallback(stockCode);
            const dateRange = getDateRange();
            const params = {
                symbol: stockCode,
                scale: 240,          // 日K线
                ma: '5,10',         // 显示5日和10日均线
                datalen: parseInt(document.getElementById('daysInput').value) * 2 || 20,  // 获取两倍的数据以确保能取到足够的交易日
                from: dateRange.from,
                to: dateRange.to
            };

            const url = `${baseUrl}/${callback}/CN_MarketDataService.getKLineData?${new URLSearchParams(params)}`;
            
            const script = document.createElement('script');
            script.id = `jsonp-script-${stockCode}`;
            script.src = url;
            script.onerror = function() {
                stockDataMap[stockCode] = 'error';
                displayAllData();
            };
            
            document.body.appendChild(script);
        }

        // 格式化数字为带两位小数的字符串
        function formatNumber(num) {
            if (num === null || num === undefined || isNaN(num)) {
                return '-';
            }
            return parseFloat(num).toFixed(2);
        }

        // 计算涨跌幅
        function calculateChange(current, previous) {
            if (!previous) return '-';
            const change = ((current - previous) / previous * 100);
            return change > 0 ? `+${change.toFixed(2)}%` : `${change.toFixed(2)}%`;
        }

        // 显示所有股票数据
        function displayAllData() {
            const container = document.getElementById('stockData');
            const stockCards = Object.entries(stockDataMap).map(([code, data]) => {
                if (!data) {
                    return `
                        <div class="stock-card error">
                            <h3>${code}</h3>
                            <p>暂无数据</p>
                        </div>
                    `;
                }
                if (data === 'error') {
                    return `
                        <div class="stock-card error">
                            <h3>${code}</h3>
                            <p>获取数据失败</p>
                        </div>
                    `;
                }

                // 只取前10个交易日的数据
                const days = parseInt(document.getElementById('daysInput').value) || 10;
                const recentData = data.slice(0, days);
                
                // 生成数据行
                const dataRows = recentData.map((day, index) => {
                    const changePercent = calculateChange(
                        day.close,
                        index < recentData.length - 1 ? recentData[index + 1].close : null
                    );
                    return `
                        <tr class="${parseFloat(changePercent) > 0 ? 'up' : parseFloat(changePercent) < 0 ? 'down' : ''}">
                            <td>${day.day}</td>
                            <td>${formatNumber(day.open)}</td>
                            <td>${formatNumber(day.close)}</td>
                            <td>${formatNumber(day.high)}</td>
                            <td>${formatNumber(day.low)}</td>
                            <td>${changePercent}</td>
                            <td>${(day.volume / 10000).toFixed(2)}万</td>
                            <td>${formatNumber(day.ma_price5)}</td>
                            <td>${formatNumber(day.ma_price10)}</td>
                        </tr>
                    `;
                }).join('');

                return `
                    <div class="stock-card">
                        <h3>${code}</h3>
                        <div class="stock-info">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>日期</th>
                                        <th>开盘</th>
                                        <th>收盘</th>
                                        <th>最高</th>
                                        <th>最低</th>
                                        <th>涨跌幅</th>
                                        <th>成交量</th>
                                        <th>MA5</th>
                                        <th>MA10</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${dataRows}
                                </tbody>
                            </table>
                        </div>
                    </div>
                `;
            }).join('');

            container.innerHTML = stockCards;
        }

        // 复制 Markdown 内容
        function handleCopyMarkdown() {
            const markdown = generateMarkdown(stockDataMap);
            navigator.clipboard.writeText(markdown).then(() => {
                const copyBtn = document.getElementById('copyMarkdown');
                const originalText = copyBtn.textContent;
                copyBtn.textContent = '复制成功';
                copyBtn.classList.add('success');
                
                setTimeout(() => {
                    copyBtn.textContent = originalText;
                    copyBtn.classList.remove('success');
                }, 2000);
            }).catch(err => {
                alert('复制失败，请重试');
                console.error('复制失败:', err);
            });
        }
    </script>

    <style>
        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            font-family: Arial, sans-serif;
        }
        
        .title {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
        }

        .search-box {
            margin-bottom: 30px;
            text-align: center;
        }

        .stock-input {
            width: 100%;
            max-width: 500px;
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            resize: vertical;
        }

        .search-btn {
            padding: 10px 30px;
            background-color: #2196F3;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }

        .search-btn:hover {
            background-color: #1976D2;
        }

        .data-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(600px, 1fr));
            gap: 20px;
        }

        .stock-card {
            background-color: #fff;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .stock-card h3 {
            margin: 0 0 15px 0;
            color: #333;
            text-transform: uppercase;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }

        .data-table th,
        .data-table td {
            padding: 8px;
            text-align: right;
            border-bottom: 1px solid #eee;
        }

        .data-table th:first-child,
        .data-table td:first-child {
            text-align: left;
        }

        .data-table thead th {
            background-color: #f5f5f5;
            font-weight: bold;
        }

        .data-table tr.up td {
            color: #e4393c;
        }

        .data-table tr.down td {
            color: #2eb872;
        }

        .error {
            background-color: #fff3f3;
            color: #d63031;
            text-align: center;
        }

        .loading {
            text-align: center;
            padding: 20px;
            font-size: 16px;
            color: #666;
        }

        .button-group {
            display: flex;
            gap: 10px;
            justify-content: center;
            margin-top: 10px;
        }

        .copy-btn {
            padding: 10px 30px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            transition: background-color 0.3s;
        }

        .copy-btn:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        .copy-btn:not(:disabled):hover {
            background-color: #388E3C;
        }

        .copy-btn.success {
            background-color: #388E3C;
        }

        .days-input-container {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
        }

        .days-input {
            width: 80px;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            text-align: center;
        }

        @media (max-width: 768px) {
            .data-container {
                grid-template-columns: 1fr;
            }
            
            .data-table {
                font-size: 12px;
            }
            
            .data-table th,
            .data-table td {
                padding: 6px 4px;
            }
        }
    </style>
</body>
</html> 